﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;


namespace ToDoWebRole
{
    public class IdentityDataSource
    {
        /**/
      
       /***/
        //Azure Table Storage source
          private IdentityDataServiceContext context = null;

            //Connect to storage. Create context. Lazy initialize table.
            public IdentityDataSource()
            {
                //Connect to storage
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
     configSetter(ConfigurationManager.AppSettings[configName]));
                //Aditi commented this var sa = CloudStorageAccount.FromConfigurationSetting("AzureConnectionString");
                var sa = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                //Create context
                context = new IdentityDataServiceContext(sa.TableEndpoint.ToString(), sa.Credentials);

                //Ensure that table exists
                var cloudClient = sa.CreateCloudTableClient();
                if (cloudClient.DoesTableExist(IdentityDataServiceContext.IdentityTableName) == false)
                {
                    //Strictly speaking, this is a race condition -- table could come into existence from other source while this block executes. We can ignore it for our purposes. 
                    cloudClient.CreateTableIfNotExist(IdentityDataServiceContext.IdentityTableName);

                }

                //Ensure that the _ROOT task exists. Ditto race condition possibility, ditto ignore.
                if (!context.IdentityTable.ToList<IdentityDataModel>().Any(t => t.ID == IdentityDataModel.ROOT_ID))
                {
                    var root = new IdentityDataModel(IdentityDataModel.ROOT_ID, String.Empty);
                    root.ID = IdentityDataModel.ROOT_ID;
                    root.UserId = 777;
                    root.GroupId = 777;
                    //root.longitude = "(Dont know too)";
                    Insert(root);
                }
            }

            //Generic "Select"
            public IEnumerable<IdentityDataModel> Select()
            {
                var rs = from todo in context.IdentityTable select todo;
                var query = rs.AsTableServiceQuery<IdentityDataModel>();
                return query.Execute();
            }

            private void Insert(IdentityDataModel loc)
            {
                context.AddObject(IdentityDataServiceContext.IdentityTableName, loc);
                context.SaveChanges();
            }
        


        /**/


    }

}

       
 
